package com.ty.springbootjapthymeleaf.service.impl;//package com.ty.jpa.service.impl;

import com.ty.springbootjapthymeleaf.entity.Role;
import com.ty.springbootjapthymeleaf.entity.User;
import com.ty.springbootjapthymeleaf.repository.UsrRepository;
import com.ty.springbootjapthymeleaf.service.UsrService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * UserServiceImpl
 *
 * @aurhor Administrator  whs
 * @since 2024/8/29
 */
@Service
public class UsrServiceImpl implements UsrService {

    @Resource
    private UsrRepository usrRepository;

    public UsrServiceImpl(UsrRepository usrRepository) {
        this.usrRepository = usrRepository;
    }


    /**
     * 动态查询的复杂分页查询
     *
     * @param param
     * @param pageable
     */
    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return usrRepository.findAll((Specification<User>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (param.get("usrName") != null){
                list.add(cb.like(root.get("usrName"),"%"+param.get("usrName")+"%"));
            }
            if (param.get("usrRoleId") != null){
                list.add(cb.equal(root.get("usrRoleId"),param.get("usrRoleId")));
            }

            return cb.and(list.toArray(new Predicate[list.size()]));
        },pageable);
    }

    /**
     * 动态查询的复杂分页查询
     *
     * @param usrName
     * @param usrRoleId
     * @param pageable
     */

    public Page<User> findByUsrNameAndUsrRoleId(String usrName, Long usrRoleId, Pageable pageable) {
        Specification<User> specification = new Specification<User>() {
                @Override
                public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> list = new ArrayList<>();
                    if (usrName != null && !"".equals(usrName)){
                        list.add(cb.like(root.get("usrName"),"%"+usrName+("usrName")+"%"));
                    }
                    if (usrRoleId != null &&  usrRoleId.longValue()!= 01){
                        Role role = new Role();
                        role.setRoleId(usrRoleId);

                        list.add(cb.equal(root.get("usrRoleId"),usrRoleId));
                    }

                    return cb.and(list.toArray(new Predicate[list.size()]));
                }
            };
        return usrRepository.findAll(specification, pageable);
        }


}
